package com.fingard.dsp.bank.directbank.zjrc01;

import java.io.File;
import java.text.DecimalFormat;
import java.util.Date;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.PaymentState;
import com.fingard.dsp.bank.directbank.bankInterface.IBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqQryBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.RetAtsBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.RetAtsQryBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.detail.RetAtsBatPayRecDetail;
import com.fingard.io.FileHelper;
import com.fingard.net.ConnState;
import com.fingard.text.StringHelper;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

public class ZJRC01BatPayRec extends ZJRC01Base implements IBatPayRec {
    private static final String STR_FORMAT = "000000";
    DecimalFormat decimalFormat = new DecimalFormat(STR_FORMAT);
    //1988
    public RetAtsBatPayRec d_1988_BatPay(ReqBatPayRec p_req1988) throws Exception {
        return d_BatPayRec(p_req1988);
    }

    //9188
    @Override
    public RetAtsBatPayRec d_9188_BatPay(ReqBatPayRec p_req9188) throws Exception {
        return null;
    }

    //批量代收和代发工资提交
    public RetAtsBatPayRec d_BatPayRec(ReqBatPayRec p_reqBat) throws Exception {

        RetAtsBatPayRec retAts = new RetAtsBatPayRec(p_reqBat.reqHeader);
        serialNo = p_reqBat.reqHeader.reqSeqID;
        try {
            tranCode = "100008";//代发代报销
            XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
            writeCommonHeader(xmlWriter);
            xmlWriter.writeElementString("payAccount", p_reqBat.ownAct);//need
            xmlWriter.writeElementString("type", "1");//类型 need 1.代发 2.代报销
            xmlWriter.writeElementString("payMonth", Format.Date6YearMonth.format(new Date()));
            //代发9121：工资9122：奖金1214：养老金1218：伙食费1304：股息2114：红利9189：冷饮费代报销
            //默认为9121
            xmlWriter.writeElementString("bdrantCode","9121");//代发/代报销摘要代码 need
            int count = 1;
            if(Integer.parseInt(p_reqBat.totalNum)>500){
                retAts.respCode = "0";
                retAts.respInfo = "超过代发代报销批量支付最大支持总笔数,最大为500笔";
                retAts.reqSeqID = p_reqBat.reqBatchNO;
                retAts.transState = PaymentState.FAIL_Batch;
                retAts.payInfoCode = ConnState.FAIL;
                retAts.writeRetToATS();
                return retAts;
            }
            xmlWriter.writeStartElement("iSalaryRecordList");
            while (p_reqBat.readRecord()) {
                xmlWriter.writeStartElement("row");
                xmlWriter.writeElementString("employeeId",decimalFormat.format(count));
                xmlWriter.writeElementString("employeeName", p_reqBat.readedDetail.recName);
                xmlWriter.writeElementString("cardNo", p_reqBat.readedDetail.recAct);
                xmlWriter.writeElementString("payAmount", p_reqBat.readedDetail.payAmount);
                xmlWriter.writeElementString("comment", p_reqBat.readedDetail.askNumber);//传入对账码
                xmlWriter.writeEndElement();
                count++;
            }
            xmlWriter.writeEndElement();
            xmlWriter.writeEndElement();
            xmlWriter.writeEndDocument();//写入报文完成
            String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());//发送银行
//            String[] tmpStrRet = {"","<?xml version=\"1.0\" encoding=\"GBK\" ?><ebank><resHead><retCode>0000</retCode><errMsg/><resDate>20181106</resDate><resTime>143026618</resTime><custNo>1000296270</custNo><userId>000000</userId><tranCode>100008</tranCode><serialNo>RN000005EJ</serialNo><reqDate>20181106</reqDate><reqTime>142410065</reqTime></resHead><resBody><batchNo>301811068000254</batchNo></resBody></ebank>"};
            //模拟银行返回
            /*tmpStrRet[0] = "";
            tmpStrRet[1] ="<?xml version=\"1.0\" encoding=\"GBK\"?>\n" +
                    "<ebank>\n" +
                    "\t<resHead>\n" +
                    "\t\t<retCode>0000</retCode>\n" +
                    "\t\t<errMsg>返回错误信息</errMsg>\n" +
                    "\t\t<serialNo>12345678</serialNo>\n" +
                    "\t</resHead>\n" +
                    "\t<resBody>\n" +
                    "\t\t\t\t<batchNo>9876543</batchNo>\n" +
                    "\t</resBody>\n" +
                    "</ebank>\n";*/
            if (tmpStrRet[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                //解析银行返回 去除后缀无用信息
                int index = tmpStrRet[1].indexOf("</ebank>");
                tmpStrRet[1] = tmpStrRet[1].substring(0,index+8);
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    String tmpStatus = tmpBkReader.getFirstText("/ebank/resHead/retCode");
                    String tmpInfo = tmpBkReader.getFirstText("/ebank/resHead/errMsg");
                    String batchNo = tmpBkReader.getFirstText("/ebank/resBody/batchNo");
                    if (tmpStatus != null && tmpStatus.length() > 0) {
                        retAts.respCode = "0";
                        retAts.reqSeqID = p_reqBat.reqBatchNO;
                        retAts.respInfo = tmpInfo;
                        retAts.transState = tmpStatus;
                        retAts.payInfoCode = retAts.transState;
                        String filename = getBankConfig().getValueAsString("saveDir")+ File.separator+Format.Date8Format.format(new Date())
                                +File.separator+retAts.reqSeqID+".txt";
                        FileHelper.writeFile(filename,batchNo,"gbk");
                    }
                } else {
                    retAts.respCode = "-1";
                    retAts.respInfo = tmpSbMsg.toString();
                }
            } else if (tmpStrRet[0].equals(ConnState.FAIL)) {
                retAts.respCode = "0";
                retAts.respInfo = tmpStrRet[1];
                retAts.reqSeqID = p_reqBat.reqBatchNO;
                retAts.transState = PaymentState.FAIL_Batch;
                retAts.payInfoCode = tmpStrRet[0];
            } else {
                retAts.respCode = "-1";
                retAts.respInfo = tmpStrRet[1];
            }

        } catch (Exception e) {
            retAts.respCode = "-1";
            retAts.respInfo = e.toString();
            e.printStackTrace();
        }
        if (retAts.respCode.equals("-1") && StringHelper.isNullOrEmpty(retAts.reqSeqID)) {
            retAts.reqSeqID = p_reqBat.reqBatchNO;
        }
        retAts.writeRetToATS();
        return retAts;
    }

    //1998 状态查询
    public RetAtsQryBatPayRec d_1998_QryBatPay(ReqQryBatPayRec p_req1998) throws Exception {
        return d_QryBatPayRec(p_req1998);
    }

    //9198
    @Override
    public RetAtsQryBatPayRec d_9198_QryBatPay(ReqQryBatPayRec p_req9198) throws Exception {
        return null;
    }

    //批量代付和工资代付状态查询
    public RetAtsQryBatPayRec d_QryBatPayRec(ReqQryBatPayRec p_reqQryBat) throws Exception {
        //返回ATS的对象
        RetAtsQryBatPayRec retAts = new RetAtsQryBatPayRec(p_reqQryBat.reqHeader);
        serialNo = p_reqQryBat.reqHeader.reqSeqID;
        tranCode = "100010";
        XmlTextWriter xmlWriter;
        xmlWriter = new XmlTextWriter();//发银行报文的XML对象
        writeCommonHeader(xmlWriter);//写入通用的头部节点
        xmlWriter.writeElementString("flowNoType","0");
        String filename = getBankConfig().getValueAsString("saveDir")+ File.separator+p_reqQryBat.bgnDate.substring(0,10).replaceAll("-","")
                +File.separator+p_reqQryBat.reqBatchNO+".txt";
        if(!FileHelper.existFile(filename)){
            throw new Exception("存放银行批次号的文件不存在,请和银行确认该交易!");
        }
        String batchNo = FileHelper.readFileText(filename,"gbk");
        xmlWriter.writeElementString("batchNo", batchNo);
        xmlWriter.writeEndElement();
        xmlWriter.writeEndDocument();
        try {
            String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());
//            String[] tmpStrRet = {"","<?xml version=\"1.0\" encoding=\"GBK\" ?><ebank><resHead><retCode>0000</retCode><errMsg/><resDate>20181112</resDate><resTime>134500503</resTime><custNo>1000296270</custNo><userId>000000</userId><tranCode>100010</tranCode><serialNo>RN000008HO</serialNo><reqDate>20181112</reqDate><reqTime>133826380</reqTime></resHead><resBody><batchNo>301811128000274</batchNo><corpSN>RN000008HO</corpSN><payAccount>201000190123718</payAccount><batchStt>91</batchStt><totalNum>3</totalNum><totalAmt>3.00</totalAmt><submitTime>20181112121452</submitTime><batchErrorMessage>交易失败</batchErrorMessage><wageflowResultList><row><recAccount>101014862981321</recAccount><recAccountName>亚历山大</recAccountName><amount>1.00</amount><empNo>000001</empNo><remark>CC000008HO</remark><state>91</state><errorMessage/></row><row><recAccount>101014862740417</recAccount><recAccountName>张飞</recAccountName><amount>1.00</amount><empNo>000002</empNo><remark>CC000008HO</remark><state>91</state><errorMessage/></row><row><recAccount>101014862981583</recAccount><recAccountName>刘浩</recAccountName><amount>1.00</amount><empNo>000003</empNo><remark>CC000008HO</remark><state>91</state><errorMessage/></row></wageflowResultList></resBody></ebank><!--DjJ2pqVaEpbsbuNyNkRVNEiLHKak+/9u5x9nthonOgL0bGs8De5+ivFemmh0IdMfQJH4DZyWf8SpCTTtMXQ1hIjxFqvx50mY9Iwicz4bXmIThw8PBMhmE4oqIDWMQX47aNwuKo9QVqQE3rvvV2mHlxF7uy70CHBIKsLXFaZ8vC4CKc/P3HNCYcRYA9y2w9p8nshIgv/bRBcRDnlcKy9NE5YnMT7xvhQURhj5G0gXcVtkMMUcIJxC4bdUyuTRcouSi7iP+G1jYC7H7x4TS89P11/HdUXrTy3BxwRtmMG1nDuE3BdAbFLfbWnmyLUQaB+z++uJ3r6yTgCjfonbZbBTog==-->"};
            //模拟银行返回
            /*tmpStrRet[0] = "";
            tmpStrRet[1] ="<?xml version=\"1.0\" encoding=\"GBK\"?>\n" +
                    "<ebank>\n" +
                    "\t<resHead>\n" +
                    "\t\t<retCode>0000</retCode>\n" +
                    "\t\t<errMsg>返回错误信息</errMsg>\n" +
                    "\t\t<serialNo>12345678</serialNo>\n" +
                    "\t</resHead>\n" +
                    "\t<resBody>\n" +
                    "\t<batchNo>123456</batchNo>\n" +
                    "\t<corpSN>123456</corpSN>\n" +
                    "\t<payAccount>330278671358</payAccount>\n" +
                    "\t<batchStt>90</batchStt>\n" +
                    "\t<totalNum>3</totalNum>\n" +
                    "\t<totalAmt>25.00</totalAmt>\n" +
                    "\t<orderSubmitTime></orderSubmitTime>\n" +
                    "\t<batchErrorMessage>核心错误信息</batchErrorMessage>\n" +
                    "\t\t<wageflowResultList>\n" +
                    "\t\t\t<row>\n" +
                    "\t\t\t\t<recAccount>8976</recAccount>\n" +
                    "\t\t\t\t<recAccountName>CESHI供转账用</recAccountName>\n" +
                    "\t\t\t\t<state>90</state>\n" +
                    "\t\t\t\t<amount>333.00</amount>\n" +
                    "\t\t\t\t<empNo>工号</empNo>\n" +
                    "\t\t\t\t<remark>CC000000MD</remark>\n" +
                    "\t\t\t\t<state>90</state>\n" +
                    "\t\t\t\t<errorMessage>核心错误消息</errorMessage>\n" +
                    "\t\t\t</row>\n" +
                    "\t\t\t<row>\n" +
                    "\t\t\t\t<recAccount>8976</recAccount>\n" +
                    "\t\t\t\t<recAccountName>CESHI供转账用</recAccountName>\n" +
                    "\t\t\t\t<state>90</state>\n" +
                    "\t\t\t\t<amount>1234.00</amount>\n" +
                    "\t\t\t\t<empNo>工号</empNo>\n" +
                    "\t\t\t\t<remark>CC000000MD</remark>\n" +
                    "\t\t\t\t<state>90</state>\n" +
                    "\t\t\t\t<errorMessage>核心错误消息</errorMessage>\n" +
                    "\t\t\t</row>\n" +
                    "\t\t\t<row>\n" +
                    "\t\t\t\t<recAccount>8976</recAccount>\n" +
                    "\t\t\t\t<recAccountName>CESHI供转账用</recAccountName>\n" +
                    "\t\t\t\t<state>90</state>\n" +
                    "\t\t\t\t<amount>121.00</amount>\n" +
                    "\t\t\t\t<empNo>工号</empNo>\n" +
                    "\t\t\t\t<remark>CC000000MD</remark>\n" +
                    "\t\t\t\t<state>90</state>\n" +
                    "\t\t\t\t<errorMessage>核心错误消息</errorMessage>\n" +
                    "\t\t\t</row>\n" +
                    "\t\t</wageflowResultList>\n" +
                    "\t</resBody>\n" +
                    "</ebank>\n";*/
            if (tmpStrRet[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                int index = tmpStrRet[1].indexOf("</ebank>");
                tmpStrRet[1] = tmpStrRet[1].substring(0,index+8);
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    String retCode = tmpBkReader.getFirstText("/ebank/resHead/retCode");
                    String tmpStatus = tmpBkReader.getFirstText("/ebank/resHead/retCode")+"+"+tmpBkReader.getFirstText("/ebank/resBody/batchStt");
                    String tmpStatusText = tmpBkReader.getFirstText("/ebank/resHead/errMsg");
                    String tmpStatusText1= tmpStatusText.length()>0?tmpStatusText+" "+tmpBkReader.getFirstText("/ebank/resBody/batchErrorMessage"):tmpBkReader.getFirstText("/ebank/resBody/batchErrorMessage");
                    if (tmpStatus != null && tmpStatus.length() > 0) {
                        retAts.respCode = "0";
                        retAts.reqSeqID = p_reqQryBat.reqBatchNO;
                        int tmpCountRow = tmpBkReader.countElement("/ebank/resBody/totalNum");
                        if (tmpCountRow>0&&("0000+90".equals(tmpStatus))) {
                            retAts.writeBeforeDetail();
                            String payAct = tmpBkReader.getFirstText("/ebank/resBody/payAccount");
                            while (tmpBkReader.read("/ebank/resBody/wageflowResultList/row")) {
                                RetAtsBatPayRecDetail tmpRetDetail = new RetAtsBatPayRecDetail();
                                tmpRetDetail.payAct = payAct;
                                tmpRetDetail.recAct = tmpBkReader.readedXElement.getSingleText("recAccount");
                                tmpRetDetail.recName = tmpBkReader.readedXElement.getSingleText("recAccountName");
                                tmpRetDetail.payAmount = tmpBkReader.readedXElement.getSingleText("amount");
                                tmpRetDetail.result = retCode +"+"+tmpBkReader.readedXElement.getSingleText("state");
                                tmpRetDetail.postScript = tmpBkReader.readedXElement.getSingleText("remark");//加入一个编号来确认这条记录信息
                                tmpRetDetail.usage = tmpBkReader.readedXElement.getSingleText("remark");
                                tmpRetDetail.payInfoCode = tmpRetDetail.result;
                                retAts.writeRetDetail(tmpRetDetail);
                            }
                        } else if(tmpCountRow > 0){
                            retAts.respCode = "0";
                            retAts.respInfo = tmpStatusText1;
                            retAts.reqSeqID = p_reqQryBat.reqBatchNO;
                            retAts.transState = tmpStatus;
                            retAts.payInfoCode = retAts.transState;
                        }else if (tmpCountRow == 0) {
                            retAts.respCode = "-1";
                            retAts.respInfo = "状态查询结果为空";
                        } else {
                            retAts.respCode = "-1";
                            retAts.respInfo = tmpStatusText1;
                        }
                    } else {
                        retAts.respCode = "-1";
                        retAts.respInfo = tmpStatusText1;
                    }
                } else {
                    retAts.respCode = "-1";
                    retAts.respInfo = tmpSbMsg.toString();
                }
            } else {
                retAts.respCode = "-1";
                retAts.respInfo = tmpStrRet[1];
            }
        } catch (Exception e) {
            retAts.respCode = "-1";
            retAts.respInfo = e.getMessage();
            e.printStackTrace();
        }
        if (retAts.respCode.equals("-1") && StringHelper.isNullOrEmpty(retAts.reqSeqID)) {
            retAts.reqSeqID = p_reqQryBat.reqBatchNO;
        }
        if (retAts.respCode.equals("-1")) {
            retAts.writeBeforeDetail();
        }
        retAts.writeAfterDetail();
        return retAts;
    }

}
